package top.wuyang.study.javawebjdbc.worknews;

import top.wuyang.study.javawebjdbc.dao.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TbNewsDAO {

    public static int insert(TbNews tbNews) throws SQLException {
        Connection conn = DBHelper.getConnection();
        String sql = "insert into tb_news (title,connent) value(?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,tbNews.getTitle());
        ps.setString(2,tbNews.getConnent());
        int i = ps.executeUpdate();
        conn.close();
        return i;

    }

    public static List<TbNews> query() throws SQLException {
        List<TbNews> list = new ArrayList<>();
        Connection conn = DBHelper.getConnection();
        String sql = "select * from tb_news";
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            TbNews tbNews = new TbNews();
            tbNews.setId(rs.getInt("id"));
            tbNews.setTitle(rs.getString("title"));
            tbNews.setConnent(rs.getString("connent"));
            tbNews.setPublishdate(rs.getTimestamp("publishdate"));
            list.add(tbNews);
        }
        conn.close();
        return list;

    }

    public static int delete(Integer id) throws SQLException {
        Connection conn = DBHelper.getConnection();
        String sql = "delete from tb_news where id = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1,id);
        int i = ps.executeUpdate();
        conn.close();
        return i;
    }




}
